

#import "CitysController.h"
#import "PinYinForObjc.h"
#import "ChineseInclude.h"
#import "CityModel.h"
#import "CharacterCell.h"
#import "HotcityView.h"
#import "HotCity.h"
#import "CGFdbmBase.h"
#import "UINavigationController+FDFullscreenPopGesture.h"
#define VW self.view.bounds.size.width
#define VH self.view.bounds.size.height
#define WeightRate VW/375
#define HeightRate VH/667
#define CellHeight 45*HeightRate
#define HeaderHeight 10*HeightRate
#define TableViewHeaderFontSize 13*HeightRate
#define TableViewCellFontSize 16*HeightRate
@interface CitysController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,UISearchResultsUpdating,UISearchDisplayDelegate,UIGestureRecognizerDelegate>
{
    UITableView *tabelMain;
    
    NSMutableArray *_searchResults;
    UISearchController  * _searchController;
    UIView *_view;
    CGFloat _tableHight;
}
@property (nonatomic,strong) NSDictionary *cityDic;
@property (nonatomic,strong) NSArray *CityHead;
@property (nonatomic,strong) UIView *head;
@property (nonatomic,strong) NSMutableArray *cityPinyAry;
@property (nonatomic,strong) NSMutableArray *cityPYHeadAry;
@end

@implementation CitysController

-(NSMutableArray *)cityPYHeadAry{
    if (!_cityPYHeadAry) {
        _cityPYHeadAry = [NSMutableArray array];
        
        [_cityPYHeadAry addObjectsFromArray:[CGFdbmBase SeachWhithPath:@"diaoyur_city" AndTableName:@"region_city" IdStrName:@"py"]];
    }
    
    return _cityPYHeadAry;
}
-(NSMutableArray *)cityPinyAry{
    
    if (!_cityPinyAry) {
        
        _cityPinyAry = [NSMutableArray array];
        [_cityPinyAry addObjectsFromArray:[CGFdbmBase SeachWhithPath:@"diaoyur_city" AndTableName:@"region_city" IdStrName:@"pinyin"]];
        
    }
    return _cityPinyAry;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.app.myTabBar.tabBar.hidden = YES;
    self.navigationController.navigationBar.hidden = NO;
      self.navigationController.navigationBarHidden = NO;
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = NO;
    StatusBlack;
}

- (void)backLastView{
    [self.navigationController popViewControllerAnimated:NO];
    
}

-(void)SetNaView{
    self.navigationItem.title = @"切换城市";
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:19],NSForegroundColorAttributeName:[UIColor blackColor]}];
    
    UIButton  *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftBtn setImage:[UIImage imageNamed:@"btn-return"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(backLastView) forControlEvents:UIControlEventTouchUpInside];
    leftBtn.frame = CGRectMake(0, 0,10, 25);
    leftBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -3, 0, 0);
    UIBarButtonItem  *leftItem =[[UIBarButtonItem alloc]initWithCustomView: leftBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self SetNaView];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    /**
     *  读取本地数据库  获取所有城市 用于搜索
     */
    [[Manager sharedManager]CityDataFromSQL:^(id Model, id Citys) {
        self.ModelAry = Model;
        self.cityAry = Citys;
    }];

    _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    _searchController.searchResultsUpdater = self;
    _searchController.searchBar.delegate = self;
    _searchController.hidesNavigationBarDuringPresentation = NO;
    _searchController.dimsBackgroundDuringPresentation = false;
    _searchController.searchBar.placeholder = @"输入城市名或拼音查询";
    _searchController.searchBar.frame = CGRectMake(0, 0, _searchController.searchBar.frame.size.width, 44);
    [_searchController.searchBar sizeToFit];
    _searchController.searchBar.searchBarStyle = UISearchBarStyleMinimal;
    [_searchController.searchBar setBackgroundImage:[[UIImage alloc] init]];
    
    
    [self.view addSubview:_searchController.searchBar];
    
    
//    //监听键盘
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardWillHideNotification object:nil];
    
    
    self.cityDic = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"citiesGroups" ofType:@"plist"]];
    self.CityHead = @[@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"J",@"K",@"L",@"M",@"N",@"P",@"Q",@"R",@"S",@"T",@"W",@"X",@"Y",@"Z"];
    
    [self addTableView];
    [self addAlphabetButton];
    
}

#pragma mark--右边字母列表
- (void) addAlphabetButton
{
    //26字母view
    _view = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH*(1-0.06),44+40, SCREEN_WIDTH*0.06,SCREEN_HEIGHT-(40+44)*2)];
    [self.view addSubview:_view];
    
    float w = _view.bounds.size.width;
    float h = _view.bounds.size.height/self.CityHead.count;//每个字母的间距
    
    for (int i=0; i<self.CityHead.count; i++) {
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, h*i, w, h)];
        [button setTitle:self.CityHead[i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor colorWithRed:85/256.0 green:171/256.0 blue:247/256.0 alpha:1.0] forState:UIControlStateNormal];
        button.titleLabel.font = font(10);
        [button addTarget:self action:@selector(touchAlphabetButton:) forControlEvents:UIControlEventTouchUpInside];
        [_view addSubview:button];
    }
}
- (void) touchAlphabetButton:(UIButton *)sender
{
    NSIndexPath *scollIndex = [NSIndexPath indexPathForRow:0 inSection:[self.CityHead indexOfObject:sender.titleLabel.text]];
    [tabelMain scrollToRowAtIndexPath:scollIndex atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

- (void)keyboardDidShow:(NSNotification *)notification
{
    if (_searchController.searchBar.text.length==0) {
         _searchController.active = NO;
        tabelMain.tableHeaderView = self.head;
    }
}
//具体调用的时候使用的方法也发生了改变，这个时候使用updateSearchResultsForSearchController进行结果过滤:
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
  
    NSString *searchText = [_searchController.searchBar text];
            _searchResults = [[NSMutableArray alloc]init];
    
    if (searchText.length>0&&![ChineseInclude isIncludeChineseInString:searchText]) {
        
        for (int i=0; i<_cityAry.count; i++) {
            
            if ([ChineseInclude isIncludeChineseInString:_cityAry[i]]) {
                if(searchText.length == 1){
                    
                    NSString *tempPinYinStr = self.cityPinyAry[i];
                    
                    NSRange titleResult=[tempPinYinStr rangeOfString:searchText options:NSCaseInsensitiveSearch];
                    
                    if (titleResult.length>0) {
                        
                        [_searchResults addObject:_cityAry[i]];
                    }
                }else{
                    
                    NSString *tempPinYinStr = self.cityPinyAry[i];
                    
                    NSRange titleResult=[tempPinYinStr rangeOfString:searchText options:NSCaseInsensitiveSearch];
                    if (titleResult.length>0) {
                        
                        [_searchResults addObject:_cityAry[i]];
                        
                    }
                    NSString *tempPinYinHeadStr = self.cityPYHeadAry[i];
                    
                    NSRange titleHeadResult=[tempPinYinHeadStr rangeOfString:searchText options:NSCaseInsensitiveSearch];
                    if (titleHeadResult.length>0) {
                        
                        [_searchResults addObject:_cityAry[i]];
                        
                    }
                }
            }
            else {
                NSRange titleResult=[_cityAry[i] rangeOfString:searchText options:NSCaseInsensitiveSearch];
                if (titleResult.length>0) {
                    
                    [_searchResults addObject:_cityAry[i]];
                }
            }
        }
    } else if (searchText.length>0&&[ChineseInclude isIncludeChineseInString:searchText]) {
        //中文搜索
        
        for (NSString *tempStr in _cityAry) {
            NSRange titleResult=[tempStr rangeOfString:searchText options:NSCaseInsensitiveSearch];
            if (titleResult.length>0) {
                
                [_searchResults addObject:tempStr];
            }
        }
        
    }
    
                [tabelMain reloadData];

                if (_searchController.active) {
                    _view.alpha =0;
                }else{
                
                    _view.alpha =1;
                }
}



- (void)addTableView
{
    tabelMain = [[UITableView alloc] initWithFrame:CGRectMake(0,Height(_searchController.searchBar), VW, VH) style:UITableViewStylePlain];
    tabelMain.delegate = self;
    tabelMain.dataSource = self;
    tabelMain.showsVerticalScrollIndicator = NO;
    tabelMain.bounces =NO;
    tabelMain.tableFooterView = [UIView new];
    [tabelMain registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.view addSubview:tabelMain];
    [self CrectTableviewOfHotcity];
}
#pragma mark--tableview头部 显示当前城市和热门城市
-(void)CrectTableviewOfHotcity{
    
    _head = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 230)];
    
    HotcityView *local = [[HotcityView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 70)];
    local.title.text = @"当前城市";
    if (_localCity!=nil) {
        local.cityAry = @[_localCity];
    }
    [_head addSubview:local];
    
    _hot = [[HotcityView alloc]initWithFrame:CGRectMake(0,Height(local), SCREEN_WIDTH, 160)];
    _hot.title.text = @"热门城市";
    
    NSMutableArray *hotCitys = [NSMutableArray array];
    for (HotCity *model in _hoteCity) {
        [hotCitys addObject:model.short_name];
    }

    __weak typeof(self) weakself = self;
    _hot.MyBlock = ^(UIButton *sender){
        weakself.CityBlock(sender.currentTitle);
        [weakself.navigationController popViewControllerAnimated:YES];
    };
    
    _hot.cityAry = [hotCitys copy];
    [_head addSubview:_hot];
    tabelMain.tableHeaderView = _head;
}

#pragma mark - TableView Delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
       return CellHeight;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_searchController.active) {
        tabelMain.tableHeaderView = nil;
        return 1;
    }else {
        return self.CityHead.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section;
{
    if (_searchController.active){
        
        return 0;
    }
        return 20;
}

#pragma mark - TableView DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
       if (_searchController.active) {
        return _searchResults.count;
    }
    else {
        
        NSArray *ary = [self.cityDic valueForKey:self.CityHead[section]];
        return ary.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.textLabel.font = [UIFont fontWithName:@"GillSans-Light" size:TableViewCellFontSize];
    cell.textLabel.textColor = [UIColor colorWithWhite:0 alpha:1];
    
    if (_searchController.active) {
        cell.textLabel.text = _searchResults[indexPath.row];
    }else {
        
        NSArray *ary = [self.cityDic valueForKey:self.CityHead[indexPath.section]];
        CityModel *model = [[CityModel alloc]initWithDictionary:ary[indexPath.row] error:nil];
        cell.textLabel.text =model.short_name;
    }
    
    //设置分割线的风格
    tabelMain.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    
    //设置分割线距边界的距离
    [tabelMain setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 20)];
    return cell;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UILabel *label = [[UILabel alloc]init];
    label.text =[NSString stringWithFormat:@"\t%@", self.CityHead[section]];
    label.font = [UIFont fontWithName:@"GillSans-Light" size:TableViewHeaderFontSize+6];
    label.textColor = [UIColor colorWithWhite:0 alpha:0.8];
    label.backgroundColor =RGBA(221, 220, 224, 1);
    return label;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
   
    if (_CityBlock) {
        
        if (cell.textLabel.text.length>4) {
            cell.textLabel.text = [NSString stringWithFormat:@"%@...",[cell.textLabel.text substringToIndex:3]];
        }
        _CityBlock(cell.textLabel.text);
    }
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    if (_searchController.active) {
        _searchController.active = NO;
        [_searchController.searchBar removeFromSuperview];
    }
}

-(void)dealloc{
      [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
@end